package com.wonderful.mall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wonderful.mall.member.entity.MemberLevelEntity;
import com.wonderful.mall.member.exception.MobileExistException;
import com.wonderful.mall.member.exception.UsernameExistException;
import com.wonderful.mall.member.service.MemberLevelService;
import com.wonderful.mall.member.util.HttpUtils;
import com.wonderful.mall.member.vo.MemberLoginVo;
import com.wonderful.mall.member.vo.MemberRegisterVo;
import com.wonderful.mall.member.vo.SocialUser;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wonderful.common.utils.PageUtils;
import com.wonderful.common.utils.Query;

import com.wonderful.mall.member.dao.MemberDao;
import com.wonderful.mall.member.entity.MemberEntity;
import com.wonderful.mall.member.service.MemberService;

import javax.annotation.Resource;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {
    @Resource
    MemberLevelService memberLevelService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void register(MemberRegisterVo vo) {
        MemberEntity memberEntity = new MemberEntity();
        MemberDao memberDao = this.baseMapper;
        //设置默认等级
        MemberLevelEntity levelEntity = memberLevelService.getDefaultLevel();
        memberEntity.setLevelId(levelEntity.getId());
        //检查用户名和手机号是否唯一
        checkMobileUnique(vo.getMobile());
        CheckUserNameUnique(vo.getUserName());
        //设置手机号
        memberEntity.setMobile(vo.getMobile());
        //设置用户名
        memberEntity.setUsername(vo.getUserName());
        //密码加密存储
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        memberEntity.setPassword(encoder.encode(vo.getPassword()));
        memberDao.insert(memberEntity);
    }

    @Override
    public void checkMobileUnique(String mobile) throws MobileExistException{
        MemberDao memberDao = this.baseMapper;
        if (memberDao.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", mobile))>1)
            throw new MobileExistException();
    }

    @Override
    public void CheckUserNameUnique(String username) throws UsernameExistException{
        MemberDao memberDao = this.baseMapper;
        if (memberDao.selectCount(new QueryWrapper<MemberEntity>().eq("username", username))>1)
            throw  new UsernameExistException();
    }

    @Override
    public MemberEntity login(SocialUser vo) throws Exception {
        MemberDao memberDao = this.baseMapper;
        MemberEntity member = memberDao.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", vo.getUid()));
        if (member!=null){
            //用户已经注册
            member.setAccessToken(vo.getAccessToken());
            member.setExpiresIn(vo.getExpiresIn());
            member.setSocialUid(vo.getUid());
            Map<String,String> query = new HashMap<>();
            query.put("access_token",vo.getAccessToken());
            query.put("uid",vo.getUid());
            HttpResponse response = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "get", new HashMap<>(), query);
            if (response.getStatusLine().getStatusCode()==200){
                String s = EntityUtils.toString(response.getEntity());
                JSONObject jsonObject = JSON.parseObject(s);
                String name = jsonObject.getString("name");
                member.setNickname(name);
            }
            memberDao.update(member,new QueryWrapper<MemberEntity>().eq("social_uid",vo.getUid()));
            return member;
        }else {
            //没有查到当前社交用户对应的记录
            MemberEntity entity = new MemberEntity();
            entity.setCreatedAt(vo.getCreatedAt());
            entity.setAccessToken(vo.getAccessToken());
            entity.setExpiresIn(vo.getExpiresIn());
            entity.setSocialUid(vo.getUid());
            Map<String,String> query = new HashMap<>();
            query.put("access_token",vo.getAccessToken());
            query.put("uid",vo.getUid());
            HttpResponse response = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "get", new HashMap<>(), query);
            if (response.getStatusLine().getStatusCode()==200){
                String s = EntityUtils.toString(response.getEntity());
                JSONObject jsonObject = JSON.parseObject(s);
                String name = jsonObject.getString("name");
                entity.setNickname(name);
            }
            memberDao.insert(entity);
            return entity;
        }
    }

    @Override
    public MemberEntity login(MemberLoginVo vo) {
        String loginAcct = vo.getLoginAcct();
        String password = vo.getPassword();
        MemberEntity entity = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("username", loginAcct).or().eq("mobile", loginAcct));
        if (entity==null){
            return null;
        }else {
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            if (encoder.matches(password,entity.getPassword())) {
                return entity;
            }else {
                return null;
            }
        }
    }
}